<template>
  <div class="page-container">
    <EmergencyVerticalTabNav />
    
    <div class="material-category-container">
      <!-- 顶部操作栏 -->
      <div class="operation-bar">
        <div class="left">
          <span class="page-title">物资分类管理</span>
        </div>
        <div class="button-area">
          <el-button type="primary" plain @click="handleAdd()">
            <el-icon><Plus /></el-icon> 新增分类
          </el-button>
          <el-button type="info" plain @click="handleToggleExpandAll">
            <el-icon><Sort /></el-icon> {{ isExpandAll ? '折叠' : '展开' }}
          </el-button>
          <el-button type="primary" plain @click="getList">
            <el-icon><Refresh /></el-icon> 刷新
          </el-button>
        </div>
      </div>

      <div v-loading="loading" class="loading-container">
        <el-card shadow="hover" class="card-container">
          <template #header>
            <div class="card-header">
              <div class="title-area">
                <h2 class="card-title">物资分类管理</h2>
              </div>
            </div>
          </template>

          <div class="card-content">
            <el-table
              max-height="780px"
              ref="categoryTableRef"
              :data="categoryList"
              row-key="id"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              :default-expand-all="isExpandAll"
              :expand-row-keys="expandedRowKeys"
              style="width: 100%"
              size="default"
            >
              <el-table-column prop="name" label="分类名称" min-width="260" />
              <!-- <el-table-column prop="categoryId" label="上级分类ID" align="center" width="200" /> -->
              <el-table-column label="创建人" align="center" width="220">
                <template #default="{ row }">
                  {{ getUserName(row.createBy) }}
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" width="220">
                <template #default="{ row }">
                  {{ row.createTime ? formatDate(row.createTime) : '-' }}
                </template>
              </el-table-column>
              <el-table-column label="修改人" align="center" width="220">
                <template #default="{ row }">
                  {{ getUserName(row.updateBy) }}
                </template>
              </el-table-column>
              <el-table-column label="修改时间" align="center" width="220">
                <template #default="{ row }">
                  {{ row.updateTime ? formatDate(row.updateTime) : '-' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="220" fixed="right" align="center">
                <template #default="scope">
                  <el-tooltip content="修改" placement="top">
                    <el-button
                      type="primary"
                      link
                      @click="handleUpdate(scope.row)"
                    ><el-icon><Edit /></el-icon></el-button>
                  </el-tooltip>
                  <el-tooltip content="新增" placement="top">
                    <el-button
                      type="primary"
                      link
                      @click="handleAdd(scope.row)"
                    ><el-icon><Plus /></el-icon></el-button>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <el-button
                      type="danger"
                      link
                      @click="handleDelete(scope.row)"
                    ><el-icon><Delete /></el-icon></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>

      <el-dialog
        v-model="modalVisible"
        :title="modalTitle"
        width="500px"
        destroy-on-close
        append-to-body
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item v-if="form.categoryId !== 0" label="上级分类" prop="categoryId">
            <el-tree-select
              v-model="form.categoryId"
              :data="categoryOptions"
              :props="{ children: 'children', label: 'name', value: 'id' }"
              placeholder="选择上级分类"
              :check-strictly="true"
              default-expand-all
              class="w-full"
            />
          </el-form-item>
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入分类名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelModal">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete, Refresh, Sort } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import {
  getSupplyCategoryInfo,
  addSupplyCategoryInfo,
  updateSupplyCategoryInfo,
  deleteSupplyCategoryInfo,
  getSupplyCategoryInfoById
} from '@/api/bridge/bisc/car';
import { getUserInfoList } from '@/api/bridge/user/user';
import EmergencyVerticalTabNav from '../components/EmergencyVerticalTabNav.vue';

// 定义分类项类型接口
interface CategoryItem {
  id: number | string;
  name: string;
  categoryId: number | string;
  createBy: number | null;
  updateBy: number | null;
  createTime: string | null;
  updateTime: string | null;
  children?: CategoryItem[];
  [key: string]: any;
}

// 定义用户信息接口
interface UserInfo {
  userId: number;
  userName: string;
  nickName: string;
  [key: string]: any;
}

// 定义表单数据接口
interface FormData {
  id?: number | string;
  name: string;
  categoryId: number | string;
}

// 日期格式化函数
function formatDate(date: string | number | Date) {
  if (!date) return '-';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hour = String(d.getHours()).padStart(2, '0');
  const minute = String(d.getMinutes()).padStart(2, '0');
  const second = String(d.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

// 路由实例
const router = useRouter();

// 状态变量定义
const categoryList = ref<CategoryItem[]>([]);
const categoryOptions = ref<CategoryItem[]>([]);
const userList = ref<UserInfo[]>([]);
const loading = ref(true);
const isExpandAll = ref(false);
const expandedRowKeys = ref<string[]>([]);
const modalVisible = ref(false);
const modalTitle = ref('');
const categoryTableRef = ref();
const formRef = ref();

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 100000, // 获取全部数据用于构建树形结构
});

// 初始化表单数据
const initFormData: FormData = {
  id: undefined,
  name: '',
  categoryId: 0,
};

// 表单数据和验证规则
const form = ref<FormData>({ ...initFormData });
const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择上级分类', trigger: 'change' }],
};

// 获取用户列表数据
const getUserList = async () => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 100000, // 获取较大数量的用户
    };
    const res = await getUserInfoList(params);
    userList.value = res.rows || [];
    console.log('获取的用户列表数据:', userList.value);
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  }
};

// 根据用户ID获取用户名称
const getUserName = (userId: number | null) => {
  if (!userId) return '-';
  const user = userList.value.find(user => user.userId === userId);
  return user ? user.nickName || user.userName : `用户${userId}`;
};

// 获取所有分类的ID，用于展开/折叠
const getAllCategoryIds = (list: CategoryItem[]): string[] => {
  let ids: string[] = [];
  
  list.forEach(item => {
    ids.push(String(item.id));
    if (item.children && item.children.length > 0) {
      ids = [...ids, ...getAllCategoryIds(item.children)];
    }
  });
  
  return ids;
};

// 获取分类列表数据
const getList = async () => {
  loading.value = true;
  try {
    const res = await getSupplyCategoryInfo(queryParams.value);
    // 假设返回的数据已经是树形结构
    categoryList.value = res.rows || [];
    console.log('获取的分类列表数据:', categoryList.value);
    
    // 默认展开所有行
    if (isExpandAll.value) {
      expandedRowKeys.value = getAllCategoryIds(categoryList.value);
    } else {
      expandedRowKeys.value = [];
    }
    
    loading.value = false;
  } catch (error) {
    console.error('获取分类列表失败:', error);
    ElMessage.error('获取分类列表失败');
    loading.value = false;
  }
};

// 获取分类选项（用于下拉选择）
const getCategoryOptions = async () => {
  try {
    const res = await getSupplyCategoryInfo(queryParams.value);
    categoryOptions.value = res.rows || [];
  } catch (error) {
    console.error('获取分类选项失败:', error);
    ElMessage.error('获取分类选项失败');
  }
};

// 展开/折叠操作
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  
  if (isExpandAll.value) {
    // 展开全部
    expandedRowKeys.value = getAllCategoryIds(categoryList.value);
  } else {
    // 折叠全部
    expandedRowKeys.value = [];
  }
  
  // 强制刷新表格状态
  nextTick(() => {
    console.log('展开状态变更:', isExpandAll.value, '展开的行:', expandedRowKeys.value);
  });
};

// 取消模态框
const cancelModal = () => {
  modalVisible.value = false;
  form.value = { ...initFormData };
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 处理添加分类
const handleAdd = (row?: CategoryItem) => {
  modalTitle.value = '添加分类';
  form.value = { ...initFormData };
  
  if (row && row.id) {
    form.value.categoryId = row.id;
  } else {
    form.value.categoryId = 0; // 作为顶级分类
  }
  
  getCategoryOptions(); // 获取分类选项
  modalVisible.value = true;
};

// 处理更新分类
const handleUpdate = async (row: CategoryItem) => {
  modalTitle.value = '修改分类';
  
  try {
    // 可以直接使用行数据或者通过API获取详情
    form.value = {
      id: row.id,
      name: row.name,
      categoryId: row.categoryId
    };
    
    getCategoryOptions(); // 获取分类选项
    modalVisible.value = true;
  } catch (error) {
    console.error('获取分类详情失败:', error);
    ElMessage.error('获取分类详情失败');
  }
};

// 处理删除分类
const handleDelete = (row: CategoryItem) => {
  ElMessageBox.confirm(
    `确定要删除"${row.name}"分类吗？删除后将无法恢复，且可能影响关联的物资数据。`,
    '确认删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteSupplyCategoryInfo(row.id);
      ElMessage.success('删除成功');
      getList();
    } catch (error) {
      console.error('删除分类失败:', error);
      ElMessage.error('删除分类失败');
    }
  }).catch(() => {
    // 取消删除操作
  });
};

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const submitData: any = {
          name: form.value.name,
          categoryId: form.value.categoryId
        };
        
        if (form.value.id !== undefined) {
          // 更新操作
          submitData.id = form.value.id;
          await updateSupplyCategoryInfo(submitData);
          ElMessage.success('修改成功');
        } else {
          // 新增操作
          await addSupplyCategoryInfo(submitData);
          ElMessage.success('添加成功');
        }
        
        modalVisible.value = false;
        getList(); // 刷新列表
      } catch (error) {
        console.error('提交表单失败:', error);
        ElMessage.error('操作失败');
      }
    }
  });
};

// 页面选择相关
const currentPageValue = ref('categories');
const pageOptions = ref([
  { label: '物资管理', value: 'resources' },
  { label: '物资分类', value: 'categories' },
  { label: '应急知识', value: 'knowledge' },
  { label: '救援队伍', value: 'teams' }
]);

// 页面跳转处理
const handlePageChange = (value: string) => {
  if (value === 'resources') {
    router.push('/monitor/emergency-resources');
  } else if (value === 'categories') {
    router.push('/coordination-command/material-categories');
  } else if (value === 'knowledge') {
    router.push('/coordination-command/emergency-knowledge');
  } else if (value === 'teams') {
    router.push('/coordination-command/rescue-teams');
  }
};

onMounted(() => {
  getUserList(); // 获取用户列表数据
  getList(); // 获取分类列表数据
  
  // 设置初始展开状态为折叠
  isExpandAll.value = false;
  // 初始化时设置展开的行
  nextTick(() => {
    expandedRowKeys.value = isExpandAll.value ? getAllCategoryIds(categoryList.value) : [];
  });
});
</script>

<style scoped lang="scss">
.page-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  overflow: hidden;
}

.material-category-container {
  flex: 1;
  padding: 20px;
  overflow: auto;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.card-container {
  margin-bottom: 20px;
  background: var(--el-bg-color-overlay);
  width: 100%;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: var(--el-box-shadow);
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    bottom: -10px;
    left: 0;
    width: 0;
    height: 1px;
    background: var(--el-border-color-light);
    transition: width 0.5s ease;
  }
  
  &:hover::after {
    width: 100%;
  }
}

.title-area {
  display: flex;
  align-items: center;
}

.card-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    left: -100%;
    bottom: 0;
    width: 100%;
    height: 2px;
    background: var(--el-color-primary);
    transition: left 0.5s ease;
  }
  
  &:hover::before {
    left: 0;
  }
}

.button-area {
  display: flex;
  gap: 10px;
  transition: all 0.3s ease;
  
  &:hover {
    transform: scale(1.02);
  }
}

.operation-buttons {
  display: flex;
  gap: 8px;
}

:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-light);
  --el-table-header-bg-color: var(--el-bg-color-page);
  --el-table-row-hover-bg-color: var(--el-fill-color-light);
  
  .el-table__header-wrapper th {
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
  
  .el-table__row td {
    padding: 12px 16px;
    color: var(--el-text-color-regular);
  }
}

:deep(.el-select-dropdown__item.is-active) {
  color: var(--el-color-primary);
  font-weight: bold;
  background-color: var(--el-color-primary-light-9);
}

:deep(.el-input__wrapper) {
  background-color: var(--el-bg-color-overlay);
}

:deep(.el-input__wrapper:hover) {
  background-color: var(--el-fill-color-light);
}

:deep(.el-input__inner) {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

:deep(.el-dialog) {
  border-radius: 12px;
  background: var(--el-bg-color-overlay);
  transform: scale(0.9);
  opacity: 0;
  transition: all 0.3s ease;

  &.el-overlay-dialog-wrapper {
    transition: opacity 0.3s ease;
  }

  &.is-visible {
    transform: scale(1);
    opacity: 1;
  }

  .el-dialog__header {
    background: var(--el-bg-color-page);
    margin: 0;
    padding: 20px;
    border-bottom: 1px solid var(--el-border-color-light);
  }

  .el-dialog__body {
    padding: 30px 20px;
    animation: slideDown 0.4s ease-out;
  }

  .el-dialog__footer {
    border-top: 1px solid var(--el-border-color-light);
    padding: 15px 20px;
  }
}

@keyframes slideDown {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}

:deep(.el-tree-select__popper) {
  .el-select-dropdown__item {
    height: auto;
    padding: 8px 20px;
  }

}

.w-full {
  width: 100%;
}

.loading-container {
  position: relative;
  min-height: 200px;
  width: 100%;
  
  &:deep(.el-loading-mask) {
    background-color: rgba(255, 255, 255, 0.7);
    backdrop-filter: blur(2px);
    
    .el-loading-spinner {
      .path {
        stroke-width: 3;
      }
      
      .el-loading-text {
        animation: pulse 1.5s infinite;
      }
    }
  }
}

@keyframes pulse {
  0% { opacity: 0.6; }
  50% { opacity: 1; }
  100% { opacity: 0.6; }
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  background: var(--el-bg-color-overlay);
  padding: 16px;
  border-radius: 4px;

  .left {
    display: flex;
    align-items: center;
  }

  .button-area {
    display: flex;
    gap: 10px;
  }
}

.page-selector {
  width: 180px;
  
  :deep(.el-input__wrapper) {
    background-color: transparent;
    box-shadow: none !important;
    
    &:hover {
      background-color: var(--el-fill-color-light);
    }
  }

  :deep(.el-input__inner) {
    font-size: 16px;
    font-weight: 500;
    color: var(--el-color-primary);
  }

  :deep(.el-select-dropdown__item) {
    &.is-active {
      color: var(--el-color-primary);
      font-weight: bold;
      background-color: var(--el-color-primary-light-9);
    }

    &:hover {
      background-color: var(--el-color-primary-light-9);
    }
  }
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}
</style> 